<template>
  <div 
    class="ai-chat-float" 
    @dblclick="openAIChat"
    @mousedown="startDrag"
    :style="{ right: position.right + 'px', bottom: position.bottom + 'px' }"
  >
    <div class="ai-chat-icon">
      <img src="/images/jqr.gif" alt="AI智能助手" />
    </div>
    <div class="ai-chat-pulse"></div>
  </div>

  <!-- 温馨提示 -->
  <div v-if="tipVisible" class="ai-chat-tip" :style="tipStyle">
    {{ tipMessage }}
  </div>

  <lay-layer v-model="aiChatVisible" type="1" title="AI智能助手" :area="['50%', '50%']">
    <div class="ai-chat-dialog">
    
      
      <div class="chat-messages" ref="chatMessagesRef">
        <div
          v-for="(message, index) in chatMessages"
          :key="index"
          :class="['message', message.type]"
        >
          <div class="message-avatar" v-if="message.type === 'ai'">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
            </svg>
          </div>
          <div class="message-avatar" v-else>
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
              <circle cx="12" cy="7" r="4"></circle>
            </svg>
          </div>
          <div class="message-content">
            <div class="message-text">{{ message.content }}</div>
          </div>
        </div>
      </div>
      
      <div class="chat-input-container">
        <div class="chat-input-wrapper">
          <lay-input
            v-model="userInput"
            placeholder="请输入您的问题..."
            @keyup.enter="sendAIMessage"
            :disabled="isStreaming"
            class="ai-input"
          ></lay-input>
          <lay-button
            v-if="!isStreaming"
            type="primary"
            @click="sendAIMessage"
            :disabled="!userInput.trim()"
            class="send-button"
          >
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <line x1="22" y1="2" x2="11" y2="13"></line>
              <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
            </svg>
          </lay-button>
          <lay-button
            v-else
            type="danger"
            @click="stopStreaming"
            class="stop-button"
          >
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <rect x="6" y="4" width="4" height="16"></rect>
              <rect x="14" y="4" width="4" height="16"></rect>
            </svg>
          </lay-button>
        </div>
        <div class="input-hint">按 Enter 发送，Shift + Enter 换行</div>
      </div>
    </div>
  </lay-layer>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, onMounted, onBeforeUnmount } from "vue";

export default defineComponent({
  name: "AIChat",
  setup() {
    const aiChatVisible = ref(false);
    const userInput = ref("");
    const chatMessages = ref([
      { type: "ai", content: "您好！我是AI助手，有什么我可以帮您的吗？" },
    ]);
    const chatMessagesRef = ref(null);
    const tipVisible = ref(false);
    const tipMessage = ref("");
    const tipStyle = reactive({
      right: '20px',
      bottom: '90px'
    });
    const isStreaming = ref(false); // 是否正在流式传输
    let abortController: AbortController | null = null; // 中断控制器

    // 悬浮按钮位置状态
    const position = reactive({
      right: 20,
      bottom: 20,
      isMoved: false // 标记是否被移动过
    });

    // 拖拽相关状态
    const dragState = reactive({
      isDragging: false,
      startX: 0,
      startY: 0,
      startRight: 0,
      startBottom: 0
    });

    // 开始拖拽
    const startDrag = (e: MouseEvent) => {
      if (e.button !== 0) return; // 只响应左键点击
      
      // 隐藏提示信息
      tipVisible.value = false;
      
      dragState.isDragging = true;
      dragState.startX = e.clientX;
      dragState.startY = e.clientY;
      dragState.startRight = position.right;
      dragState.startBottom = position.bottom;
      
      // 添加全局事件监听器
      document.addEventListener('mousemove', onDrag);
      document.addEventListener('mouseup', stopDrag);
      
      // 阻止默认行为，避免选中文本等
      e.preventDefault();
    };

    // 拖拽中
    const onDrag = (e: MouseEvent) => {
      if (!dragState.isDragging) return;
      
      const deltaX = e.clientX - dragState.startX;
      const deltaY = e.clientY - dragState.startY;
      
      // 计算新位置
      let newRight = dragState.startRight - deltaX;
      let newBottom = dragState.startBottom - deltaY;
      
      // 获取视口尺寸
      const viewportWidth = window.innerWidth;
      const viewportHeight = window.innerHeight;
      
      // 限制拖拽范围，确保元素在视口内
      newRight = Math.max(10, Math.min(viewportWidth - 70, newRight));
      newBottom = Math.max(10, Math.min(viewportHeight - 70, newBottom));
      
      position.right = newRight;
      position.bottom = newBottom;
      
      // 标记按钮已被移动
      if (!position.isMoved && (Math.abs(deltaX) > 5 || Math.abs(deltaY) > 5)) {
        position.isMoved = true;
      }
    };

    // 停止拖拽
    const stopDrag = () => {
      dragState.isDragging = false;
      
      // 移除全局事件监听器
      document.removeEventListener('mousemove', onDrag);
      document.removeEventListener('mouseup', stopDrag);
    };

    // 显示提示信息
    const showTip = (message: string) => {
      tipMessage.value = message;
      tipVisible.value = true;
      updateTipPosition();
      
      // 5秒后自动隐藏
      setTimeout(() => {
        tipVisible.value = false;
      }, 5000);
    };

    // 更新提示信息位置
    const updateTipPosition = () => {
      tipStyle.right = (position.right + 30) + 'px'; // 以按钮中心为基准
      tipStyle.bottom = (position.bottom + 80) + 'px'; // 在按钮上方
    };

    // 双击打开AI聊天窗口
    const openAIChat = (e: MouseEvent) => {
      // 如果是拖拽操作，则不打开聊天窗口
      if (dragState.isDragging) return;
      
      // 显示操作提示
      showTip("双击打开AI助手，可以拖拽移动位置");
      
      // 只有当按钮未被移动过时才居中显示
      if (!position.isMoved) {
        centerFloatButton();
      }
      aiChatVisible.value = true;
    };

    // 居中悬浮按钮
    const centerFloatButton = () => {
      const viewportWidth = window.innerWidth;
      const viewportHeight = window.innerHeight;
      
      position.right = (viewportWidth - 60) / 2;
      position.bottom = (viewportHeight - 60) / 2;
      
      // 更新提示位置
      updateTipPosition();
    };

    // 发送消息
    const sendAIMessage = async () => {
      if (!userInput.value.trim() || isStreaming.value) return;

      // 添加用户消息
      const userMessage = userInput.value;
      chatMessages.value.push({
        type: "user",
        content: userMessage,
      });

      // 清空输入框
      userInput.value = "";

      // 添加AI回复占位符
      const aiMessageIndex = chatMessages.value.length;
      chatMessages.value.push({
        type: "ai",
        content: ""
      });

      // 开始流式传输
      await streamAIResponse(userMessage, aiMessageIndex);
    };

    // 流式获取AI回复
    const streamAIResponse = async (question: string, messageIndex: number) => {
      isStreaming.value = true;
      
      try {
        abortController = new AbortController();
        
        const response = await fetch(`/v1/api/knowledge/stream?question=${encodeURIComponent(question)}`, {
          signal: abortController.signal
        });
        
        const reader = response.body.getReader();
        const decoder = new TextDecoder('utf-8');
        let accumulatedText = "";
        
        while (true) {
          const { done, value } = await reader.read();
          
          if (done) {
            console.log('流式传输完成');
            break;
          }
          
          // 解码文本
          const text = decoder.decode(value, { stream: true });
          accumulatedText += text;
          
          // 检查是否收到结束标记
          if (accumulatedText.includes('[END]')) {
            accumulatedText = accumulatedText.replace('[END]', '');
          }
          
          // 更新消息内容
          chatMessages.value[messageIndex].content = accumulatedText;
          
          // 滚动到底部
          scrollToBottom();
        }
      } catch (error) {
        if (error.name === 'AbortError') {
          console.log('请求被用户中断');
          chatMessages.value[messageIndex].content += '\n[已停止]';
        } else {
          console.error('流式传输错误:', error);
          chatMessages.value[messageIndex].content += '\n[错误]: ' + error.message;
        }
      } finally {
        isStreaming.value = false;
        abortController = null;
        // 滚动到底部
        scrollToBottom();
      }
    };

    // 停止流式传输
    const stopStreaming = () => {
      if (abortController) {
        abortController.abort();
        console.log('流式传输已停止');
      }
    };

    // 滚动到聊天底部
    const scrollToBottom = () => {
      if (chatMessagesRef.value) {
        chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;
      }
    };

    // 组件销毁前清理事件监听器
    onBeforeUnmount(() => {
      document.removeEventListener('mousemove', onDrag);
      document.removeEventListener('mouseup', stopDrag);
      // 如果正在流式传输，停止它
      if (abortController) {
        abortController.abort();
      }
    });

    return {
      aiChatVisible,
      userInput,
      chatMessages,
      chatMessagesRef,
      tipVisible,
      tipMessage,
      tipStyle,
      position,
      isStreaming,
      startDrag,
      openAIChat,
      sendAIMessage,
      stopStreaming,
    };
  },
});
</script>

<style scoped lang="less">
// AI聊天悬浮按钮样式
.ai-chat-float {
  position: fixed;
  width: 60px;
  height: 60px;
  cursor: pointer;
  z-index: 9999;
  border-radius: 50%;
  transition: transform 0.3s ease;
  user-select: none;
  display: flex;
  align-items: center;
  justify-content: center;
  
  &:hover {
    transform: scale(1.1);
  }
  
  .ai-chat-icon {
    width: 30px;
    height: 30px;
    background: linear-gradient(135deg, #6e8efb, #a777e3);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 2;
    
    svg {
      width: 18px;
      height: 18px;
      color: white;
    }
  }
  
  .ai-chat-pulse {
    position: absolute;
    width: 100%;
    height: 100%;
    border-radius: 50%;
    background: linear-gradient(135deg, #6e8efb, #a777e3);
    opacity: 0.7;
    animation: pulse 2s infinite;
    z-index: 1;
  }
  
  @keyframes pulse {
    0% {
      transform: scale(0.9);
      opacity: 0.7;
    }
    50% {
      transform: scale(1.1);
      opacity: 0.4;
    }
    100% {
      transform: scale(0.9);
      opacity: 0.7;
    }
  }
}

// 温馨提示样式
.ai-chat-tip {
  position: fixed;
  z-index: 10000;
  background: linear-gradient(135deg, #6e8efb, #a777e3);
  color: white;
  padding: 12px 20px;
  border-radius: 8px;
  font-size: 14px;
  white-space: nowrap;
  transform: translateX(50%);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10px);
  
  &::after {
    content: '';
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -8px;
    border: 8px solid transparent;
    border-top-color: #6e8efb;
  }
}

// AI聊天对话框样式
.ai-chat-dialog {
  display: flex;
  flex-direction: column;
  height: 350px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4edf9 100%);
  overflow: hidden;
  border-radius: 12px;
  bottom: 0;
  .chat-header {
    display: flex;
    align-items: center;
    padding: 20px;
    background: linear-gradient(135deg, #6e8efb, #a777e3);
    color: white;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    
    .ai-avatar {
      width: 50px;
      height: 50px;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;
      
      svg {
        width: 24px;
        height: 24px;
        color: white;
      }
    }
    
    .ai-info {
      h3 {
        font-size: 18px;
        font-weight: 600;
        margin: 0 0 5px 0;
      }
      
      p {
        font-size: 14px;
        margin: 0;
        opacity: 0.9;
      }
    }
  }
  
  .chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    display: flex;
    flex-direction: column;
    
    &::-webkit-scrollbar {
      width: 6px;
    }
    
    &::-webkit-scrollbar-track {
      background: rgba(0, 0, 0, 0.05);
      border-radius: 10px;
    }
    
    &::-webkit-scrollbar-thumb {
      background: linear-gradient(135deg, #6e8efb, #a777e3);
      border-radius: 10px;
    }
    
    .message {
      display: flex;
      margin-bottom: 20px;
      animation: fadeIn 0.3s ease;
      
      @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
      }
      
      .message-avatar {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
        margin-right: 12px;
        
        svg {
          width: 20px;
          height: 20px;
          color: white;
        }
      }
      
      &.ai {
        .message-avatar {
          background: linear-gradient(135deg, #6e8efb, #a777e3);
        }
      }
      
      &.user {
        flex-direction: row-reverse;
        
        .message-avatar {
          background: linear-gradient(135deg, #00b09b, #96c93d);
          margin-left: 12px;
          margin-right: 0;
        }
      }
      
      .message-content {
        max-width: 80%;
        
        .message-text {
          padding: 12px 16px;
          border-radius: 18px;
          font-size: 15px;
          line-height: 1.5;
          box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
        }
      }
      
      &.ai {
        .message-content {
          .message-text {
            background-color: white;
            border-top-left-radius: 4px;
            color: #333;
          }
        }
      }
      
      &.user {
        flex-direction: row-reverse;
        
        .message-content {
          .message-text {
            background: linear-gradient(135deg, #6e8efb, #a777e3);
            color: white;
            border-top-right-radius: 4px;
          }
        }
      }
    }
  }
  
  .chat-input-container {
    padding: 15px 20px;
    background: white;
    border-top: 1px solid #eee;
    position: absolute;
    width: 100%;
    bottom: 0;
    .chat-input-wrapper {
      display: flex;
      gap: 10px;
      align-items: flex-end;
      
      .ai-input {
        flex: 1;
        border-radius: 24px;
        border: 1px solid #e1e5e9;
        padding: 12px 20px;
        transition: all 0.3s ease;
        
        &:focus {
          border-color: #6e8efb;
          box-shadow: 0 0 0 3px rgba(110, 142, 251, 0.2);
        }
      }
      
      .send-button, .stop-button {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0;
        border: none;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease;
        
        &:hover {
          transform: scale(1.05);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
        
        svg {
          width: 18px;
          height: 18px;
        }
      }
      
      .send-button {
        background: linear-gradient(135deg, #6e8efb, #a777e3);
        border: none;
        
        &:hover {
          background: linear-gradient(135deg, #5a7df9, #9a6ae0);
        }
      }
      
      .stop-button {
        background: linear-gradient(135deg, #ff416c, #ff4b2b);
        border: none;
        
        &:hover {
          background: linear-gradient(135deg, #ff2a58, #ff3515);
        }
      }
    }
    
    .input-hint {
      font-size: 12px;
      color: #999;
      text-align: right;
      margin-top: 8px;
    }
  }
}
</style>